<template>
  <div class="dashboard-container">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span>管理员仪表盘</span>
          <span class="welcome-text">欢迎回来，{{ currentUserName }}</span>
        </div>
      </template>
      
      <!-- 数据统计卡片 -->
      <div class="stats-cards">
        <el-card shadow="hover" class="stat-card" @click="navigateTo('patients')">
          <div class="stat-content">
            <div class="stat-icon patient-icon"><i class="el-icon-user"></i></div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.patients }}</div>
              <div class="stat-label">患者总数</div>
            </div>
            <div class="stat-arrow"><i class="el-icon-arrow-right"></i></div>
          </div>
        </el-card>
        
        <el-card shadow="hover" class="stat-card" @click="navigateTo('stroke-events')">
          <div class="stat-content">
            <div class="stat-icon event-icon"><i class="el-icon-warning"></i></div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.strokeEvents }}</div>
              <div class="stat-label">卒中事件</div>
            </div>
            <div class="stat-arrow"><i class="el-icon-arrow-right"></i></div>
          </div>
        </el-card>
        
        <el-card shadow="hover" class="stat-card" @click="navigateTo('treatments')">
          <div class="stat-content">
            <div class="stat-icon treatment-icon"><i class="el-icon-medical"></i></div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.treatments }}</div>
              <div class="stat-label">治疗记录</div>
            </div>
            <div class="stat-arrow"><i class="el-icon-arrow-right"></i></div>
          </div>
        </el-card>
        
        <el-card shadow="hover" class="stat-card" @click="navigateTo('medical-institutions')">
          <div class="stat-content">
            <div class="stat-icon institution-icon"><i class="el-icon-office-building"></i></div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.institutions }}</div>
              <div class="stat-label">合作机构</div>
            </div>
            <div class="stat-arrow"><i class="el-icon-arrow-right"></i></div>
          </div>
        </el-card>
        
        <el-card shadow="hover" class="stat-card" @click="navigateTo('download-requests')">
          <div class="stat-content">
            <div class="stat-icon request-icon"><i class="el-icon-document"></i></div>
            <div class="stat-info">
              <div class="stat-number pending-requests">{{ statistics.pendingRequests }}</div>
              <div class="stat-label">待审核请求</div>
            </div>
            <div class="stat-arrow"><i class="el-icon-arrow-right"></i></div>
          </div>
        </el-card>
      </div>
      
      <!-- 数据图表区域 -->
      <div class="charts-section">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>卒中事件趋势</span>
              <el-select v-model="chartTimeRange" placeholder="时间范围" size="small">
                <el-option label="近7天" value="7days"></el-option>
                <el-option label="近30天" value="30days"></el-option>
                <el-option label="近3个月" value="3months"></el-option>
                <el-option label="近1年" value="1year"></el-option>
              </el-select>
            </div>
          </template>
          <div class="chart-container">
            <!-- 这里可以放置图表组件，暂时使用占位符 -->
            <div class="chart-placeholder">
              <i class="el-icon-loading"></i>
              <span>图表加载中...</span>
            </div>
          </div>
        </el-card>
        
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>治疗效果分布</span>
            </div>
          </template>
          <div class="chart-container">
            <!-- 这里可以放置图表组件，暂时使用占位符 -->
            <div class="chart-placeholder">
              <i class="el-icon-loading"></i>
              <span>图表加载中...</span>
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 最近活动和待办事项 -->
      <div class="activity-section">
        <el-card class="activity-card">
          <template #header>
            <div class="activity-header">
              <span>最近活动</span>
              <el-button type="text" size="small" @click="viewAllActivity">查看全部</el-button>
            </div>
          </template>
          <div class="activity-list">
            <el-timeline>
              <el-timeline-item 
                v-for="(activity, index) in recentActivities" 
                :key="index"
                :timestamp="formatTime(activity.time)"
                :type="getActivityType(activity.type)"
              >
                <div class="activity-content">
                  <span class="activity-user">{{ activity.user }}</span>
                  <span>{{ activity.content }}</span>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-card>
        
        <el-card class="todo-card">
          <template #header>
            <div class="todo-header">
              <span>待办事项</span>
              <el-badge :value="pendingTasks.length" class="todo-badge" />
            </div>
          </template>
          <div class="todo-list">
            <el-empty v-if="pendingTasks.length === 0" description="暂无待办事项" />
            <el-checkbox-group v-else v-model="completedTasks">
              <div v-for="task in pendingTasks" :key="task.id" class="todo-item">
                <el-checkbox :label="task.id" @change="handleTaskComplete($event, task)">
                  <div class="todo-content">
                    <div class="todo-title">{{ task.title }}</div>
                    <div class="todo-time">{{ formatTime(task.time) }}</div>
                  </div>
                </el-checkbox>
                <el-button 
                  v-if="task.action" 
                  type="text" 
                  size="small" 
                  @click="navigateTo(task.action)"
                >
                  处理
                </el-button>
              </div>
            </el-checkbox-group>
          </div>
        </el-card>
      </div>
      
      <!-- 系统信息和快捷操作 -->
      <div class="system-section">
        <el-card class="system-info">
          <template #header>
            <div class="section-header">
              <span>系统信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="系统版本">v1.0.0</el-descriptions-item>
            <el-descriptions-item label="最后更新">2024-01-15</el-descriptions-item>
            <el-descriptions-item label="服务器状态">正常运行</el-descriptions-item>
            <el-descriptions-item label="数据库状态">连接正常</el-descriptions-item>
          </el-descriptions>
        </el-card>
        
        <el-card class="quick-actions">
          <template #header>
            <div class="section-header">
              <span>快捷操作</span>
            </div>
          </template>
          <div class="actions-grid">
            <el-button 
              v-for="action in quickActions" 
              :key="action.key" 
              type="primary" 
              :icon="action.icon"
              @click="navigateTo(action.route)"
              plain
            >
              {{ action.name }}
            </el-button>
          </div>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 状态数据
const loading = ref(false)
const statistics = ref({
  patients: 0,
  strokeEvents: 0,
  treatments: 0,
  institutions: 0,
  pendingRequests: 0
})
const chartTimeRange = ref('30days')
const recentActivities = ref([])
const pendingTasks = ref([])
const completedTasks = ref([])

// 快速操作列表
const quickActions = [
  { key: 'add-patient', name: '添加患者', icon: 'el-icon-plus', route: '/patients' },
  { key: 'add-event', name: '添加卒中事件', icon: 'el-icon-plus', route: '/stroke-events' },
  { key: 'manage-docs', name: '管理政策文件', icon: 'el-icon-document', route: '/policy-documents' },
  { key: 'manage-news', name: '发布新闻公告', icon: 'el-icon-edit', route: '/news-announcements' },
  { key: 'check-requests', name: '审核下载请求', icon: 'el-icon-document-checked', route: '/download-requests' },
  { key: 'manage-users', name: '管理用户', icon: 'el-icon-user', route: '/admin/dashboard' }
]

// 当前用户名
const currentUserName = computed(() => {
  return localStorage.getItem('userName') || '管理员'
})

// 获取统计数据
const getStatistics = async () => {
  // 模拟获取统计数据
  // 在实际项目中，应该调用API获取真实数据
  statistics.value = {
    patients: 1568,
    strokeEvents: 982,
    treatments: 876,
    institutions: 48,
    pendingRequests: 12
  }
}

// 获取最近活动
const getRecentActivities = async () => {
  // 模拟获取最近活动数据
  recentActivities.value = [
    {
      id: 1,
      user: '张医生',
      content: '添加了新患者记录',
      time: new Date(Date.now() - 1000 * 60 * 30).toISOString(),
      type: 'add'
    },
    {
      id: 2,
      user: '李护士',
      content: '更新了患者张三的治疗记录',
      time: new Date(Date.now() - 1000 * 60 * 60 * 2).toISOString(),
      type: 'update'
    },
    {
      id: 3,
      user: '王研究员',
      content: '提交了数据下载请求',
      time: new Date(Date.now() - 1000 * 60 * 60 * 4).toISOString(),
      type: 'request'
    },
    {
      id: 4,
      user: '系统管理员',
      content: '发布了新的政策文件',
      time: new Date(Date.now() - 1000 * 60 * 60 * 8).toISOString(),
      type: 'publish'
    },
    {
      id: 5,
      user: '赵医生',
      content: '创建了新的卒中事件记录',
      time: new Date(Date.now() - 1000 * 60 * 60 * 12).toISOString(),
      type: 'add'
    }
  ]
}

// 获取待办事项
const getPendingTasks = async () => {
  // 模拟获取待办事项
  pendingTasks.value = [
    {
      id: 1,
      title: '审核12个数据下载请求',
      time: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(),
      action: 'download-requests'
    },
    {
      id: 2,
      title: '更新《卒中溶栓指南》文档',
      time: new Date(Date.now() + 1000 * 60 * 60 * 48).toISOString(),
      action: 'policy-documents'
    },
    {
      id: 3,
      title: '统计本月治疗效果数据',
      time: new Date(Date.now() + 1000 * 60 * 60 * 72).toISOString(),
      action: null
    },
    {
      id: 4,
      title: '检查系统数据备份',
      time: new Date(Date.now() + 1000 * 60 * 60 * 96).toISOString(),
      action: null
    }
  ]
}

// 导航到指定页面
const navigateTo = (route) => {
  switch (route) {
    case 'patients':
      router.push('/patients')
      break
    case 'stroke-events':
      router.push('/stroke-events')
      break
    case 'treatments':
      router.push('/treatments')
      break
    case 'medical-institutions':
      router.push('/medical-institutions')
      break
    case 'download-requests':
      router.push('/download-requests')
      break
    case 'policy-documents':
      router.push('/policy-documents')
      break
    case 'news-announcements':
      router.push('/news-announcements')
      break
    default:
      ElMessage.info('功能待实现')
  }
}

// 查看所有活动
const viewAllActivity = () => {
  ElMessage.info('查看所有活动功能待实现')
}

// 处理任务完成
const handleTaskComplete = (checked, task) => {
  if (checked) {
    ElMessage.success(`已完成任务: ${task.title}`)
  } else {
    ElMessage.info(`任务已恢复: ${task.title}`)
  }
}

// 格式化时间显示
const formatTime = (time) => {
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  
  // 小于1分钟
  if (diff < 60 * 1000) {
    return '刚刚'
  }
  // 小于1小时
  else if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`
  }
  // 小于24小时
  else if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
  }
  // 小于7天
  else if (diff < 7 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`
  }
  // 超过7天显示具体日期
  else {
    return date.toLocaleDateString()
  }
}

// 获取活动类型对应的图标类型
const getActivityType = (type) => {
  switch (type) {
    case 'add':
      return 'success'
    case 'update':
      return 'primary'
    case 'delete':
      return 'danger'
    case 'request':
      return 'warning'
    case 'publish':
      return 'info'
    default:
      return 'primary'
  }
}

// 组件挂载时获取数据
onMounted(async () => {
  loading.value = true
  try {
    await Promise.all([
      getStatistics(),
      getRecentActivities(),
      getPendingTasks()
    ])
  } catch (error) {
    ElMessage.error('获取数据失败')
    console.error('获取仪表盘数据失败:', error)
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #1a1a1a;
  min-height: 100vh;
}

.page-card {
  margin-bottom: 20px;
  background-color: #2c2c2c;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.5);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #000000;
}

/* 确保标题文字为黑色 */
.card-header span {
  color: #000000 !important;
}

.welcome-text {
  font-size: 14px;
  color: #909399;
}

/* 统计卡片样式 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #2c2c2c;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.5);
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.6);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  margin-right: 20px;
}

.patient-icon {
  background-color: #409eff;
}

.event-icon {
  background-color: #e6a23c;
}

.treatment-icon {
  background-color: #67c23a;
}

.institution-icon {
  background-color: #909399;
}

.request-icon {
  background-color: #f56c6c;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #ffffff;
  line-height: 1;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-arrow {
  color: #606266;
  font-size: 18px;
}

.pending-requests {
  color: #f56c6c;
}

/* 图表区域样式 */
.charts-section {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
  margin-bottom: 30px;
}

.chart-card {
  height: 300px;
  background-color: #2c2c2c;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.5);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #ffffff;
}

.chart-container {
  height: calc(100% - 50px);
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
}

.chart-placeholder i {
  font-size: 48px;
  margin-bottom: 10px;
}

/* 活动和待办事项样式 */
.activity-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 30px;
}

.activity-card, .todo-card {
  height: 400px;
  overflow: hidden;
  background-color: #2c2c2c;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.5);
}

.activity-header, .todo-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #ffffff;
}

.activity-list {
  height: calc(100% - 50px);
  overflow-y: auto;
}

.activity-list::-webkit-scrollbar {
  width: 6px;
}

.activity-list::-webkit-scrollbar-track {
  background: #1a1a1a;
}

.activity-list::-webkit-scrollbar-thumb {
  background: #606266;
  border-radius: 3px;
}

.activity-list::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

.activity-content {
  font-size: 14px;
  line-height: 1.5;
  color: #e0e0e0;
}

.activity-user {
  font-weight: bold;
  margin-right: 5px;
  color: #ffffff;
}

.todo-list {
  height: calc(100% - 50px);
  overflow-y: auto;
}

.todo-list::-webkit-scrollbar {
  width: 6px;
}

.todo-list::-webkit-scrollbar-track {
  background: #1a1a1a;
}

.todo-list::-webkit-scrollbar-thumb {
  background: #606266;
  border-radius: 3px;
}

.todo-list::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

.todo-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #404040;
}

.todo-content {
  flex: 1;
  margin-left: 10px;
}

.todo-title {
  font-size: 14px;
  margin-bottom: 5px;
  color: #ffffff;
}

.todo-time {
  font-size: 12px;
  color: #909399;
}

.todo-badge {
  background-color: #f56c6c;
}

/* 系统信息和快捷操作样式 */
.system-section {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 20px;
}

.system-info, .quick-actions {
  background-color: #2c2c2c;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.5);
}

.section-header {
  font-weight: bold;
  color: #ffffff;
}

.actions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 15px;
  padding: 10px 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .charts-section {
    grid-template-columns: 1fr;
  }
  
  .activity-section {
    grid-template-columns: 1fr;
  }
  
  .system-section {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .actions-grid {
    grid-template-columns: 1fr;
  }
}
</style>